package com.note.simpleshop.module.coupon.controller;

import com.note.simpleshop.constant.ErrorCode;
import com.note.simpleshop.entity.TbCoupon;
import com.note.simpleshop.exception.ExceedsLimitException;
import com.note.simpleshop.exception.NotDataException;
import com.note.simpleshop.module.coupon.service.CouponService;
import com.note.simpleshop.module.user.auth.RequestToken;
import com.note.simpleshop.module.user.auth.UserUtils;
import com.note.simpleshop.redis.RedisLock;
import com.note.simpleshop.vo.Msg;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sun.plugin.util.UIUtil;

import java.util.List;
import java.util.UUID;

/***
 *@ClaseName:CouponController
 *
 *@Decription:提供优惠劵信息
 *
 *@Author: xubingbing
 *
 *@Date:2019/3/4 0004 23:38
 */
@Api(value="优惠劵",tags = "优惠劵")
@RestController
@RequestMapping("coupon/channel")
public class CouponController {
    public static Integer count=100000;
    private final Logger logger = LoggerFactory.getLogger(CouponController.class);
    @Autowired
    private CouponService couponService;
    @ApiOperation(value = "领取优惠劵")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header")})
    @PostMapping(value = "give")
    @RequestToken
    public Msg give(String couponId) {
        String requestId= UUID.randomUUID().toString();
        Msg msg = new Msg();
        String currentUserId= UserUtils.currentUserId();
        try {
            couponService.give(currentUserId,couponId,requestId);
            msg.setErrorCode(ErrorCode.ERROR_0000);
            msg.setMsg("领取成功");
        }
        catch (NotDataException e) {
            msg.setErrorCode(ErrorCode.ERROR_1000000);
            msg.setMsg(e.getMessage());
        }
        catch (ExceedsLimitException e) {
            msg.setErrorCode(ErrorCode.ERROR_1000000);
            msg.setMsg(e.getMessage());
        }
        catch (Exception e) {
            logger.error("give error message={}",e.getMessage());
            msg.setErrorCode(ErrorCode.ERROR_1000001);
        }
        return msg;
    }
    @ApiOperation(value = "优惠劵列表", notes = "根据频道值获取优惠劵列表")
    @PostMapping(value = "index")
    public Msg<List<TbCoupon>> index(String channel) {
        Msg msg = new Msg();
        try {
            List<TbCoupon> list=couponService.findByChannel(channel);
            msg.setErrorCode(ErrorCode.ERROR_0000);
            msg.setData(list);
        }
        catch (Exception e) {
            msg.setErrorCode(ErrorCode.ERROR_1000001);
        }
        return msg;
    }
}
